﻿using System;
using System.Linq;
using MyFloridaHouse.DataAccess;
using MyFloridaHouse.libSTO;
using MyFloridaHouse.libSvCommonUtilities;
using MyFloridaHouse.libSvDTO;
using System.Net;
using Microsoft.WindowsAzure.StorageClient;
using System.Collections.Generic;
using Microsoft.WindowsAzure;

namespace MyFloridaHouse.libServiceBusinessRules
{
    public static class File
    {
        public static FileSTO GetFile(FileInfoDTO fileToGet)
        {
            FileSTO fileSTO = null;

            //TODO: change the service "GetFile" function to use flag field in FileInfo table to control if file is downloaded with GetBlobBinaryFile or GetBlobTextFile
            if (fileToGet.format.ToUpper() == "KMZ")
            {
                fileSTO = GetBlobBinaryFile(fileToGet);
            }
            else
            {
                fileSTO = GetBlobTextFile(fileToGet);
            }
            return fileSTO;
        }
        public static FileSTO GetBlobTextFile(FileInfoDTO fileToGet)
        {
            var results = new FileSTO();

#if (USETABLESTORAGE)
			try
			{
				var blobURL = fileToGet.url + "/" + fileToGet.fileName;
				var webClient = new WebClient();
				var blobFile = webClient.DownloadData(blobURL);
				var enc = System.Text.Encoding.ASCII;
				var myString = enc.GetString(blobFile);
				results.fileData = CompressionManager.Compress(myString);
				results.fileInfo = fileToGet;
			}
			catch (Exception ex)
			{
				//todo: Log exception
				results.errorMessage = ex.Message;
			}
			return results;
#else
            try
            {
                string blobURL = fileToGet.url + "/" + fileToGet.fileName;
                WebClient webClient = new WebClient();
                byte[] blobFile;
                blobFile = webClient.DownloadData(blobURL);
                System.Text.Encoding enc = System.Text.Encoding.ASCII;
                string myString = enc.GetString(blobFile);
                results.fileData = CompressionManager.Compress(myString);
                results.fileInfo = fileToGet;
            }
            catch (Exception ex)
            {
                //todo: Log exception
                results.errorMessage = ex.Message;
            }
            return results;
#endif
        }

        /// <summary>
        /// Gets the BLOB binary file.
        /// </summary>
        /// <param name="fileToGet">The file to get.</param>
        /// <returns></returns>
        public static FileSTO GetBlobBinaryFile(FileInfoDTO fileToGet)
        {
            var results = new FileSTO();

#if (USETABLESTORAGE)
			try
			{
				var blobURL = fileToGet.url + "/" + fileToGet.fileName;
				var webClient = new WebClient();
				var blobFile = webClient.DownloadData(blobURL);
				results.fileData = blobFile;
				results.fileInfo = fileToGet;
			}
			catch (Exception ex)
			{
				results.errorMessage = ex.Message;
			}
			return results;
#else
            try
            {
                string blobURL = fileToGet.url + "/" + fileToGet.fileName;
                WebClient webClient = new WebClient();
                byte[] blobFile;
                blobFile = webClient.DownloadData(blobURL);
                results.fileData = blobFile;
                results.fileInfo = fileToGet;
            }
            catch (Exception ex)
            {
                //todo: Log exception
                results.errorMessage = ex.Message;
            }
            return results;
#endif
        }

        // TODO: Delete this, it isn't getting file info, it's reading a database entry
        public static FileInfoSTO GetFileInfo()
        {
            var results = new FileInfoSTO();

            try
            {
                var dal = new DAL_CensusData();
                var queryResults = dal.GetFileInfo();
                var x = from q in queryResults
                        select q;
                results.files = x.ToList();
            }
            catch (Exception ex)
            {
                results.errorMessage = ex.Message;
            }
            return results;
        }

        public static CloudBlockBlob GetCloudBlockBlobRef(string baseURL, string container, string directory, string fileName)
        {
            CloudBlobClient blobClient = new CloudBlobClient(Constants.CloudBlobBaseURL);
            CloudBlobDirectory blobDir = blobClient.GetBlobDirectoryReference(Constants.CloudBlobContainer);
            CloudBlobDirectory subDirectory = blobDir.GetSubdirectory(Constants.CloudTimestampDirectory);
            CloudBlockBlob cloudBlockBlob = subDirectory.GetBlockBlobReference(fileName);
            return cloudBlockBlob;
        }

        public static BlobAttributes GetBlockBlobAttributes(string blobBaseURL, string blobContainer, string blobDirectory, string blobFileName)
        {
            CloudBlockBlob cloudBlockBlob = GetCloudBlockBlobRef(blobBaseURL, blobContainer, blobDirectory, blobFileName);
            cloudBlockBlob.FetchAttributes();
            return cloudBlockBlob.Attributes;
        }

        public static bool IsFileStale(DateTime clientTimeStampUTC, string blobBaseURL, string blobContainer, string blobDirectory, string blobFileName)
        {
            if (clientTimeStampUTC == null)
            {
                return true;
            }
            else
            {
                var attr = File.GetBlockBlobAttributes(blobBaseURL, blobContainer, blobDirectory, blobFileName);
                DateTime cloudTimeStampUTC = attr.Properties.LastModifiedUtc;

                if (clientTimeStampUTC < cloudTimeStampUTC)
                {
                    return true;
                }
                return false;
            }
        }



    }
}

